package com.cjx.yuanshenstartforumbackend.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cjx.yuanshenstartforumbackend.domain.vo.UserVo;
import com.cjx.yuanshenstartforumbackend.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Struct;
import java.util.concurrent.TimeUnit;

import static com.cjx.yuanshenstartforumbackend.constants.RedisConstants.LOGIN_USER_KEY;
import static com.cjx.yuanshenstartforumbackend.constants.RedisConstants.LOGIN_USER_TTL;

/**
 * @Description 刷新token的拦截器
 * @Author cjx
 * @Date 2023/12/22 20:45
 **/
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    /**
     * 手动创建对象，因为此类未被springIOC容器管理
     * @param stringRedisTemplate redis
     */
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("token");
        //判断token是否存在
        if (StrUtil.isBlank(token)) {
            //直接放行，不走下面逻辑，到业务层自然返回未登录的错误信息
            return true;
        }
        //通过token获取Redis中存储的用户信息
        String key = LOGIN_USER_KEY + token;
        String userString = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(userString)){
            return true;
        }
        //将json字符串转换为userVo对象
        UserVo user = JSONUtil.toBean(userString, UserVo.class);
        //将userVo对象存入ThreadLocal中
        UserHolder.saveUser(user);
        //刷新token有效期
        stringRedisTemplate.expire(key,LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从ThreadLocal中移除UserVo
        UserHolder.removeUser();
    }
}
